import os
import threading
import time
from threading import Thread
from multiprocessing import Process


# 计算密集型任务
def task_cpu():
    ret = 0
    for i in range(10000000):
        ret *= i


def invoke_task_cpu():
    print("本机为", os.cpu_count(), "核CPU")
    # 单线程
    start = time.time()
    for i in range(5):
        task_cpu()
    stop = time.time()
    print("单线程耗时 %s" %(stop - start))

    # 多线程
    arr = []
    start = time.time()
    for i in range(5):
        p = Thread(target=task_cpu())
        arr.append(p)
        p.start()
    for p in arr:
        p.join()
    stop = time.time()
    print("多线程耗时 %s" %(stop - start))

    # 多进程
    arr = []
    start = time.time()
    for i in range(5):
        p = Process(target=task_cpu())
        arr.append(p)
        p.start()
    for p in arr:
        p.join()
    stop = time.time()
    print("多进程耗时 %s" % (stop - start))

# IO密集型任务
def task_io():
    f = open("tmp.txt", "w")


def invoke_task_io():
    print("本机为", os.cpu_count(), "核CPU")
    # 单线程
    start = time.time()
    for i in range(500):
        task_io()
    stop = time.time()
    print("单线程耗时 %s" % (stop - start))

    # 多线程
    arr = []
    start = time.time()
    for i in range(500):
        p = Thread(target=task_io())
        arr.append(p)
        p.start()
    for p in arr:
        p.join()
    stop = time.time()
    print("多线程耗时 %s" %(stop - start))

    # 多进程
    arr = []
    start = time.time()
    for i in range(500):
        p = Process(target=task_io())
        arr.append(p)
        p.start()
    for p in arr:
        p.join()
    stop = time.time()
    print("多进程耗时 %s" % (stop - start))


# 构造器模式
def work(num):
    print("线程名称:", threading.current_thread().name, ",参数名称:", num)


def invoke_work():
    t1 = Thread(target=work, args=(3,), name="守护线程")
    t1.start()
    t1.join()
    print("主线程结束时间:", time.strftime("%Y-%m-Td %H:%M:%S"))


# 定时器
def invoke_timer():
    t = threading.Timer(5, work, args=(5,))
    t.start()
    pass



















